<template>
  <div class="dashboard min-h-screen bg-gray-100 dark:bg-gray-800 p-4">
    <header class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-800 dark:text-gray-100">AI Trade Dashboard</h1>
      <div class="flex space-x-2">
        <button class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors">
          快速预测
        </button>
        <button class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition-colors">
          AI 分析
        </button>
      </div>
    </header>
    
    <div class="grid grid-cols-12 gap-4">
      <!-- 左侧栏 -->
      <div class="col-span-3 space-y-4">
        <WatchList />
        <DataQualityIndicator />
      </div>
      
      <!-- 主要内容区 -->
      <div class="col-span-9 space-y-4">
       
        
          <div class="grid grid-cols-3 gap-4">
            <div v-if="realTimeData[currentSymbol]" class="bg-white dark:bg-gray-700 rounded-lg shadow-lg p-4">
              <h3 class="text-lg font-bold mb-4">实时行情: {{ currentSymbol }}</h3>
               <div class="space-y-2" v-if="currentStock">
                <div class="flex justify-between">
                  <span class="text-gray-600">最新价</span>
                  <span class="font-bold">{{ currentStock.price ||currentStock.close }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">涨跌幅</span>
                  <span :class="getChangeColor(currentStock)">
                    {{ currentStock.change|| 'N/A' }}%
                  </span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">成交量</span>
                  <span class="font-bold">{{ currentStock.volume || 'N/A' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">更新时间</span>
                  <span class="text-sm text-gray-500">{{ currentStock.timestamp }}</span>
                </div>
              </div>
            </div>
            <div v-else class="bg-white dark:bg-gray-700 rounded-lg shadow-lg p-4 flex items-center justify-center">
              <p class="text-gray-500">暂无实时数据{{ realTimeData }}</p>
            </div>
          </div>
       
          
          <!-- AI 评估摘要 
          -->
        

        <!-- 预测中心 -->
        <div class="bg-white dark:bg-gray-700 rounded-lg shadow-lg p-4">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-bold">预测中心</h2>
            
          </div>
          <PredictionCenter :stock="currentSymbol" v-model:timeFrame="predictionTimeFrame" />
        </div>
        <AIEvaluation :stock="currentSymbol" class="bg-white dark:bg-gray-700 rounded-lg shadow-lg p-4" />
       
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watchEffect,watch,toRefs,reactive } from 'vue'
import { useAITradeStore,useMarketDataStore } from '../store'
import errorHandler, { ErrorType, ErrorSeverity } from '../utils/error-handler'
import MarketOverview from '../components/MarketOverview.vue' 
import PredictionCenter from '../components/PredictionCenter.vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { storeToRefs } from 'pinia'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import WatchList from '../components/WatchList.vue'
import DataQualityIndicator from '../components/DataQualityIndicator.vue'
import AIEvaluation from '../components/AIEvaluation.vue'

use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
])

const marketDataStore = useMarketDataStore() 
const store = useAITradeStore()
const currentSymbol = ref('000001')
const predictionTimeFrame = ref('30min')
const updateInterval = ref(10000) // 30 seconds
// 使用计算属性访问 store 状态，确保响应式
const predictions = computed(() => store.predictions)
const { realTimeData } = storeToRefs(marketDataStore)
const historicalData = computed(() => store.historicalData)
const trainingStatus = computed(() => store.trainingStatus)
const currentStock = computed(() => {
    if (!realTimeData.value) 
        return {}
    if (!realTimeData.value[currentSymbol.value]) 
        return {}
      try{
        const sanitizedJsonString = realTimeData.value[currentSymbol.value].replace(/'/g, '"'); 
        //解析 JSON 字符串为普通对象 
        const stockObject = JSON.parse(sanitizedJsonString); 
        return stockObject
      }
      catch(e){
        console.log('解析错误', e)
        return {}
      }
})

// Computed property for historical chart option
const historicalChartOption = computed(() => {
  if (!historicalData[currentSymbol.value]) return {}

  const data = historicalData[currentSymbol.value].map(item => [item.date, item.close])
  return {
    title: {
      text: `${currentSymbol.value} 历史价格走势`,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'time',
      axisLabel: {
        formatter: (value) => {
          const date = new Date(value)
          return `${date.getMonth() + 1}/${date.getDate()}`
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '价格'
    },
    series: [{
      data: data,
      type: 'line',
      name: '收盘价'
    }],
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ]
  }
})

// Computed property for estimated completion time
const estimatedCompletionTime = computed(() => {
  if (!trainingStatus.value || trainingStatus.value.status !== 'running') return 'N/A'
  
  const totalEpochs = trainingStatus.value.total_epochs
  const currentEpoch = trainingStatus.value.current_epoch
  const elapsedTime = trainingStatus.value.elapsed_time // in seconds
  
  const remainingEpochs = totalEpochs - currentEpoch
  const timePerEpoch = elapsedTime / currentEpoch
  const remainingTime = remainingEpochs * timePerEpoch
  
  const estimatedCompletion = new Date(Date.now() + remainingTime * 1000)
  return estimatedCompletion.toLocaleString()
})

// Initialize data on component mount
onMounted(async () => {
  try {
    await store.getSystemConfig()
    await fetchData()
  
    // Set up periodic updates
    const intervalId = setInterval(fetchData, updateInterval.value)
  
    // 组件卸载时清除定时器
    onBeforeUnmount(() => {
      clearInterval(intervalId)
    })
  } catch (error) {
    errorHandler.handleError(error, ErrorType.SYSTEM, ErrorSeverity.ERROR)
  }
})

// Fetch all required data
async function fetchData() {
  try {
    await Promise.all([
      //store.getPrediction(currentSymbol.value, predictionTimeFrame.value),
      store.getRealTimeData(currentSymbol.value),
       
    ])
  } catch (error) {
    errorHandler.handleError(error, ErrorType.NETWORK, ErrorSeverity.WARNING)
  }
}

// Watch for training status changes
watchEffect(() => {
  if (store.trainingStatus?.status === 'running') {
    setTimeout(() => {
      store.getTrainingStatus(store.trainingStatus.taskId)
    }, 5000)
  }
})

// Helper functions for training status display
function getStatusColor(status) {
  switch (status) {
    case 'running': return 'text-blue-600'
    case 'completed': return 'text-green-600'
    case 'failed': return 'text-red-600'
    default: return 'text-gray-600'
  }
}
function getChangeColor(stockObject) {

  if (!stockObject.change) return 'font-bold text-gray-600 dark:text-gray-400'
  if (stockObject.change > 0) return 'font-bold text-green-600 dark:text-green-400'
  if (stockObject.change < 0) return 'font-bold text-red-600 dark:text-red-400'
     return 'font-bold text-gray-600 dark:text-gray-400'
}

function getStatusText(status) {
  switch (status) {
    case 'running': return '正在训练'
    case 'completed': return '训练完成'
    case 'failed': return '训练失败'
    default: return '未知状态'
  }
}
</script>